<!--门禁设备管理-->
<template>
  <div class="avue-crud">
    <basic-container>
      <p class="contain-title">设备管理</p>
      <div class="door-search">
        <p>设备名称</p>
        <el-input v-model.trim="nameInput" class="search-style" placeholder="请输入设备名称"></el-input>
        <p>设备号</p>
        <el-input v-model.trim="input" class="search-style" placeholder="请输入设备mac地址"></el-input>
        <p>设备类型</p>
        <el-select v-model="typevalue" class="select-style" placeholder="请选择" @change="searchEquip()">
          <el-option
              v-for="item in types"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
        <el-button icon="el-icon-search" type="primary" @click="searchEquip()">搜索</el-button>
        <el-button icon="el-icon-delete" plain type="primary" @click="resetForm()">重置</el-button>
        <el-button icon="el-icon-plus" type="primary" @click="addEquipVisible()">新增</el-button>
        <!--        <el-button type="danger">批量删除</el-button>-->
      </div>
      <br>
      <!--设备列表-->
      <el-form>
        <el-form-item>
          <el-table
              border
              stripe
              v-loading="loading"
              :cell-style="tableCellStyle"
              :data="equipData"
              :header-cell-style='tableHeaderColor'
              :row-key="(row)=>{ return row.id}"
              @selection-change="selectionChange">
<!--            <el-table-column label="全选"-->
<!--                             type="selection"-->
<!--                             :reserve-selection="true" width="55">-->
<!--            </el-table-column>-->
            <!--无数据时-->
            <template slot="empty" class="avue-empty__image">
              <img src="/img/bg/empty.svg" alt="" style="height: 50px;width: 78px">
              <p class="avue-empty__desc" style="font-size: 14px">暂无数据</p>
            </template>
            <el-table-column
                label="序号"
                type="index"
                align="center"
                width="55"
                :index="pageSize * currentPage - pageSize + 1">
            </el-table-column>
<!--            <el-table-column label="设备编号" prop="id" width="70"></el-table-column>-->
            <el-table-column label="设备类型" prop="type">
              <template slot-scope="scope">
                <p v-if="scope.row.type === 1">面板机</p>
                <p v-if="scope.row.type === 2">摄像头</p>
                <p v-if="scope.row.type === 3">扫码器</p>
                <p v-if="scope.row.type === null || scope.row.type === ''">暂无数据</p>
              </template>
            </el-table-column>
            <el-table-column label="设备名" prop="deviceName" width="145">
              <template slot-scope="scope">
                {{ scope.row.deviceName === null ? '暂无数据' : scope.row.deviceName }}
              </template>
            </el-table-column>
            <el-table-column label="设备号/mac地址" prop="macAddress" width="176">
              <template slot-scope="scope">
                {{ scope.row.macAddress === '' || scope.row.macAddress === null ? '暂无数据' : scope.row.macAddress }}
              </template>
            </el-table-column>
            <el-table-column label="ip地址" prop="ipAddress" width="176">
              <template slot-scope="scope">
                {{ scope.row.ipAddress === '' || scope.row.ipAddress === null ? '暂无数据' : scope.row.ipAddress }}
              </template>
            </el-table-column>
            <el-table-column label="设备版本" prop="deviceAppVersion">
              <template slot-scope="scope">
                {{ scope.row.deviceAppVersion === null ? '暂无数据' : scope.row.deviceAppVersion }}
              </template>
            </el-table-column>
            <el-table-column prop="direction" label="进出向">
              <template slot-scope="scope">
                <p v-if="scope.row.direction === 0">进</p>
                <p v-if="scope.row.direction === 1">出</p>
                <p v-if="scope.row.direction === null || scope.row.direction === ''">暂无数据</p>
              </template>
            </el-table-column>
            <!--            <el-table-column label="设备编号" prop="deviceId">-->
            <!--              <template slot-scope="scope">-->
            <!--                {{ scope.row.deviceId === ""||null ? '暂无数据' : scope.row.deviceId }}-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <!--            <el-table-column label="绑定组别" prop="bindGroup">-->
            <!--              <template slot-scope="scope">-->
            <!--                {{ scope.row.bindGroup === ""||null ? '暂无数据' : scope.row.bindGroup }}-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column label="在线状态" prop="onlineStatus" v-if="tend === '1'">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.onlineStatus == false" size="medium" type="danger">离线</el-tag>
                <el-tag v-if="scope.row.onlineStatus == true" size="medium" type="success">在线</el-tag>
                <span v-else>无</span>
              </template>
            </el-table-column>
            <el-table-column label="消息" prop="onlineMessage" v-if="tend === '1'">
              <template slot-scope="scope" v-if="scope.row.onlineMessage == null">无</template>
              <template slot-scope="scope" v-else>
                {{ scope.row.onlineMessage }}
              </template>
            </el-table-column>
            <el-table-column prop="deviceStatus" label="当前状态">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.deviceStatus === 0" size="medium" type="success">正常</el-tag>
                <el-tag v-if="scope.row.deviceStatus === 1" size="medium" type="danger">锁定</el-tag>
                <el-tag v-if="scope.row.deviceStatus === null" type="primary">未设置</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="140"></el-table-column>
            <el-table-column label="操作" prop="opera" width="540" v-if="tend === '1'">
              <template slot-scope="scope">
                <el-button
                    size="mini"
                    type="success"
                    @click="handleControlDevice(scope.row,110)">更新apk
                </el-button>
                <el-button
                    size="mini"
                    type="success"
                    @click="handleControlDevice(scope.row,111)">更新数据
                </el-button>
                <el-button
                    size="mini"
                    type="success"
                    @click="handleControlDevice(scope.row,112)">重启
                </el-button>
                <el-button
                    size="mini"
                    type="success"
                    @click="handleControlDevice(scope.row,113)">测试模式
                </el-button>
                <el-button
                    size="mini"
                    icon="el-icon-edit"
                    type="primary"
                    @click="handleEdit(scope.row)">编辑
                </el-button>
                <el-button
                    size="mini"
                    icon="el-icon-delete"
                    type="danger"
                    @click="handleDelete(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>

            <el-table-column label="操作" prop="opera" width="180" v-else>
              <template slot-scope="scope">
                <el-button
                    size="mini"
                    icon="el-icon-edit"
                    type="primary"
                    @click="handleEdit(scope.row)">编辑
                </el-button>
                <el-button
                    size="mini"
                    icon="el-icon-delete"
                    type="danger"
                    @click="handleDelete(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <!--分页-->
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :data="equipData"
          :current-page="currentPage"
          :page-sizes="[5,10,20,30,40,50,100]"
          :page-size="pageSize"
          style="text-align: right"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </basic-container>
    <!--新增设备弹窗-->
    <el-dialog
        :visible.sync="addItemVisible"
        title="新增设备"
        width="35%"
        :close-on-click-modal="false"
        @close="dictItemVisible" center>
      <el-form :rules="rules">
        <el-form-item class="door-search" label="设备类型" prop="type">
          <el-radio-group v-model="type" style="margin-left: 2px">
            <el-radio label="1">面板机</el-radio>
            <el-radio label="2">摄像头</el-radio>
            <el-radio label="3">扫码器</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="door-search" label="设备名" prop="deviceName">
          <el-input v-model="deviceName" class="input-style" placeholder="填写设备名" prop="deviceName"
                    style="width: 50%;margin-left: 16px"></el-input>
        </el-form-item>
        <el-form-item class="door-search" label="设备ip" prop="deviceStatus">
          <el-input v-model="ipAddress" class="input-style" placeholder="请填写设备ip" prop="ipAddress"
                    style="width: 50%;margin-left: 17px"></el-input>
        </el-form-item>
        <el-form-item class="door-search" label="mac地址" prop="macAddress" v-if="type == 1">
          <el-input v-model="macAddress" class="input-style" placeholder="填写设备mac" prop="macAddress"
                    style="width: 50%"></el-input>
        </el-form-item>
        <el-form-item class="door-search" label="设备进出" prop="direction">
          <el-radio-group v-model="direction" style="margin-left: 2px">
            <el-radio label="0">进</el-radio>
            <el-radio label="1">出</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="door-search" label="设备状态" prop="deviceStatus">
          <el-radio-group v-model="deviceStatus" style="margin-left: 2px">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">锁定</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveItemVisible()">保存</el-button>
      </div>
    </el-dialog>

    <!-- 编辑设备弹窗-->
    <el-dialog
        :visible.sync="dialogEditVisible"
        width="35%"
        title="编辑设备"
        :close-on-click-modal="false"
        @close="dictItemVisible" center>
      <el-form :rules="rules">
        <el-form-item class="door-search" label="设备类型" prop="type">
          <el-radio-group v-model="type" style="margin-left: 2px">
            <el-radio :label="1" :value="1">面板机</el-radio>
            <el-radio :label="2" :value="2">摄像头</el-radio>
            <el-radio :label="3" :value="3">扫码器</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="door-search" label="设备名" prop="deviceName">
          <el-input v-model="deviceName" class="input-style" placeholder="填写设备名" prop="deviceName"
                    style="width: 50%;margin-left: 16px"></el-input>
        </el-form-item>
        <el-form-item class="door-search" label="设备ip" prop="deviceStatus">
          <el-input v-model="ipAddress" class="input-style" placeholder="填写设备ip" prop="ipAddress"
                    style="width: 50%;margin-left: 17px"></el-input>
        </el-form-item>
        <el-form-item class="door-search" label="mac地址" prop="macAddress" v-if="type == 1">
          <el-input v-model="macAddress" class="input-style" placeholder="填写设备mac" prop="macAddress"
                    style="width: 50%"></el-input>
        </el-form-item>
        <el-form-item class="door-search" label="设备进出" prop="direction">
          <el-radio-group v-model="direction" prop="direction" style="margin-left: 2px">
            <el-radio :label="0">进</el-radio>
            <el-radio :label="1">出</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="door-search" label="设备状态" prop="deviceStatus">
          <el-radio-group v-model="deviceStatus" prop="deviceStatus" style="margin-left: 2px">
            <el-radio :label="0" value="0">正常</el-radio>
            <el-radio :label="1" value="1">锁定</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editItemVisible()">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import 'element-ui/lib/theme-chalk/index.css';
import {addEquip, delEquip, editEquip, equipList, searchEquip} from '@/api/door/equip'
import {getStore} from "@/util/store";

export default {
  name: "equip",
  data() {
    return {
      tend: getStore({ name: "tenantId" }),
      total: 0, // 总页数
      currentPage: 1, // 当前页数
      pageSize: 10, // 每页显示多少条
      path: "ws://localhost:8084/websocket/99999",
      socket: "",
      loading: true,
      input: '',
      nameInput: '',
      macInput: '',       //新增设备弹窗的搜索框
      typevalue:'',       //设备类型
      types: [{          //多选下拉框
        value: '1',
        label: '面板机'
      }, {
        value: '2',
        label: '摄像头'
      }, {
        value: '3',
        label: '扫码器'
      }],
      value: [],
      list: [],
      states: [],
      equipData: [],         //设备列表数组
      addequipData: [],      //新增设备弹窗的设备列表
      dialogEditVisible: false,
      addItemVisible: false,
      dialogDelVisible: false,
      tableCellStyle: {
        'text-align': 'center',
        'padding':'0',
      },
      tableHeaderColor: {
        'text-align': 'center',
      },
      deviceName: '',      //设备名
      macAddress: '',      //设备mac
      ipAddress:'',        //设备ip
      direction: '',       //设备进出向
      deviceStatus: '',    //设备状态
      type:'',             //设备类型
      // 表单校验
      rules: {
        deviceName: [
          {required: true, trigger: "none"}
        ],
        macAddress: [
          {required: true, trigger: "none"}
        ],
        ipAddress: [
          {required: true, trigger: "none"}
        ],
        direction: [
          {required: true, trigger: "none"}
        ],
        deviceStatus: [
          {required: true, trigger: "none"}
        ],
        type: [
          {required: true, trigger: "none"}
        ],
      }
    }
  },
  created() {
    // 实时检测刷新token
    //this.refreshToken()
  },
  mounted() {
    this.showEquipList();
    this.init()
    // window.setInterval(() => {
    //   setTimeout(() => {
    //     this.getstatus()
    //   })
    // }, 10000)
  },
  methods: {
    // getstatus() {
    //   let ids = this.equipData.map(x => {
    //     return x.id
    //   })
    //   statusEquip(ids).then(res => {
    //     if (res.data.code === 0) {
    //       var obj = res.data.data
    //       for (var k in obj) {
    //         this.equipData.map(item => {
    //           if (item.id == k) {
    //             this.$set(item, 'onlineStatus', obj[k])
    //             // item.onlineStatus = obj[k]
    //             // console.log(item)
    //           }
    //         })
    //       }
    //     }
    //   })
    // },
    showCollapse() {
      this.$store.commit('SET_COLLAPSE')
    },
    openMenu(item = {}) {
      this.$store.dispatch("GetMenu", {type: true, id: item.id}).then(data => {
        if (data.length !== 0) {
          this.$router.$avueRouter.formatRoutes(data, true);
        }
      });
    },
    init: function () {
      if(typeof(WebSocket) === "undefined"){
        alert("您的浏览器不支持socket")
      }else{
        // 实例化socket
        this.socket = new WebSocket(this.path)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },
    open: function () {
      console.log("socket连接成功")
    },
    error: function () {
      console.log("连接错误")
    },

    //获取消息
    getMessage: function (msg) {
      var obj = JSON.parse(msg.data);
      this.equipData.map(item => {
        if (item.id == obj.deviceId) {
          this.$set(item, 'onlineMessage', obj.deviceMessage)
        }
      })
    },
    send: function () {
      this.socket.send("我从socketjs端向您报告")
    },
    close: function () {
      console.log("socket已经关闭")
    },
    selectionChange(list) {
      this.$message.success('选中的数据' + JSON.stringify(list));
      console.log(list)
    },
    //展示设备列表
    showEquipList() {
      this.loading = true;
      let param = {
        'id': '',
        'size':this.pageSize,
        'current':this.currentPage,
        descs: 'create_time',  //是否倒序
      }
      equipList(param).then(res => {
        if (res.data.code === 0) {
          this.equipData = res.data.data.records;
          this.total = res.data.data.total;
          this.loading = false;
        }
        // this.getstatus()
      });
    },

    //搜索
    searchEquip() {
      if (this.input === "" && this.nameInput === "" && this.typevalue === "") {
        this.$message.error('搜索内容不能为空')
      } else {
        let param = {
          "macAddress": this.input,
          "deviceName": this.nameInput,
          "type": this.typevalue
        }
        equipList(param).then(res => {
          if (res.data.code === 0) {
            this.equipData = res.data.data.records;
          }
        });
      }
    },

    // 重置
    resetForm: function () {
      this.input = "";
      this.nameInput = "";
      this.typevalue = ""
      this.showEquipList();
    },

    //删除设备弹窗
    handleDelete: function (row) {
      this.$confirm('是否确认删除设备？删除后相关设备绑定属性全部失效，请谨慎操作', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal:false,
      }).then(function () {
        return delEquip(row.id)
      }).then(data => {
        this.$message.success('删除成功')
        this.showEquipList(this.page)
      }).catch(() => {
      })
    },

    //打开新增设备弹窗
    addEquipVisible() {
      this.addItemVisible = true
    },

    //关闭弹窗清空内容
    dictItemVisible: function () {
      this.deviceName = null;
      this.macAddress = null;
      this.ipAddress = null;
      this.direction = null;
      this.deviceStatus = null;
      this.type = null;
    },

    //新增设备 保存
    saveItemVisible: function () {
      let param = {
        "macAddress": this.macAddress,
        "ipAddress": this.ipAddress,
        "direction": this.direction,
        // "deviceAppVersion": "1.9.5",
        "deviceName": this.deviceName,
        "deviceStatus": this.deviceStatus,
        "deviceId": this.deviceId,
        "bindGroup": "",
        "type":this.type
      }
      if(this.type == ''|| this.type == null){
        this.$message.error('请选择设备类型')
        return;
      }
      if(this.deviceName == ''|| this.deviceName == null){
        this.$message.error('请填写设备名')
        return;
      }
      if(this.ipAddress == ''|| this.ipAddress == null){
        this.$message.error('请填写设备ip地址')
        return;
      }
      if(this.type == '1'){
        if(this.macAddress == '' || this.macAddress == null){
          this.$message.error('请填写设备号/mac地址')
          return;
        }
      }
      if(this.direction === ""|| this.direction == null){
        this.$message.error('请选择设备进出向')
        return;
      }
      if(this.deviceStatus === ""|| this.deviceStatus == null){
        this.$message.error('请选择设备状态')
        return;
      }
        addEquip(param).then(res => {
          this.loading = true
            this.equipData = res.data.data.records;
            this.addItemVisible = false;
            this.loading = false
            this.$message.success('添加成功')
            this.showEquipList(this.page)
        });
    },

    //编辑设备弹窗
    handleEdit(row) {
      this.dialogEditVisible = true;
      searchEquip(row.id).then(res => {
        if (res.data.code === 0) {
          let list = res.data.data;
          // let editList = []
          // editList.push(list)
          // this.editData = editList
          this.deviceName = list.deviceName;
          this.macAddress = list.macAddress;
          this.ipAddress = list.ipAddress;
          this.direction = list.direction;
          this.deviceStatus = list.deviceStatus;
          this.type = list.type;
          this.id = list.id;
        }
      });
    },

    //编辑保存
    editItemVisible:function (){
      let param = {
        "id": this.id,
        "macAddress": this.macAddress,
        "ipAddress":this.ipAddress,
        "direction": this.direction,
        // "deviceAppVersion":"1.9.5",
        "deviceName": this.deviceName,
        "deviceStatus": this.deviceStatus,
        "type":this.type,
        // "deviceId":"123456",
        // "bindGroup":"南门门禁组"
      }
      if(this.type == '' || this.type == null){
        this.$message.error('请选择设备类型')
        return;
      }
      if(this.deviceName == ''|| this.deviceName == null){
        this.$message.error('请填写设备名')
        return;
      }
      if(this.ipAddress == ''|| this.ipAddress == null){
        this.$message.error('请填写设备ip地址')
        return;
      }
      if(this.type == '1'){
        if(this.macAddress == '' || this.macAddress == null){
          this.$message.error('请填写设备号/mac地址')
          return;
        }
      }
      if(this.direction === "" || this.direction == null){
        this.$message.error('请选择设备进出向')
        return;
      }
      if(this.deviceStatus === "" || this.deviceStatus == null){
        this.$message.error('请选择设备状态')
        return;
      }
      editEquip(param).then(res => {
        this.loading = true
        if (res.data.code === 0){
          let list=res.data.data.records;
          let equipList=[]
          for(var i in list){
            equipList.push(list[i]);
          }
          this.equipData = equipList
          this.dialogEditVisible=false;
          this.loading = false
          this.$message.success('修改成功')
          this.showEquipList(this.page)
        }
      });
    },

    handleControlDevice:function(row,typeid) {
      if (row.onlineStatus == false) {
        this.$message.warning('设备离线无法操作!')
        return;
      }
      let optionType;
      switch (typeid) {
        case 110:
          optionType = '更新远程设备apk版本'
          break;
        case 111:
          optionType = '更新远程设备数据'
          break;
        case 112:
          optionType = '重启远程设备'
          break;
        case 113:
          optionType='使远程设备进入测试模式'
          break;
        default:
          this.$message({
            type: 'error',
            message: '未知错误请联系系统管理员!'
          });
          break;
          return
      }
      this.$confirm('此操作将'+optionType+', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal:false,
      }).then(() => {
        axios({
          method: 'get',
          url: '/campus/device/control',
          params: {'deviceId':row.id,'typeId':typeid},
        }) .then(res => {
          console.log(res.data)
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });

    },

    //点击页码调用
    handleCurrentChange(val){
      this.currentPage = val
      this.showEquipList()
    },

    //点击每页多少条调用
    handleSizeChange(val){
      this.pageSize = val
      this.showEquipList()
    }
  },
  destroyed () {
    // 销毁监听
    this.socket.onclose = this.close
  }
}
</script>

<style scoped>
.contain-title{
  font-weight: bold;
  margin-left: 2px;
}
.door-search p {
  font-size: 14px;
  display: inline-block;
  margin-right: 20px;
  margin-left: 4px;
}
.search-style {
  width: 20% !important;
  margin-right: 20px;
}
.select-style {
  width: 20%!important;
  margin-right: 20px;
}
.input-style {
  width: 36% !important;
}
/deep/ .el-table__empty-block {
  padding: 60px 0;
}
/deep/ .el-table__empty-text {
  line-height: 10px;
}
</style>
